import {OutPutBuffer} from "./OutPutBuffer";

const MaxZBuffer = 10000000;
export class ZBuffer extends OutPutBuffer {
    min: number = 0;
    max: number = 0;
    mid: number = 0;
    depth: number = 0;

    constructor(width: number, height: number, yFlip: boolean = false) {
        super(width, height, 1, yFlip);
        this.setBackground([MaxZBuffer]);
    }

    private setRange(min: number, max: number) {
        this.min = Math.min(min, max);
        this.max = Math.max(min, max);
        this.depth = this.max - this.min;
        // this.setBackground([this.min]);
        // this.clear();
    }

    getPositionZ(x: number, y: number): number {
        return this.data[y*this.width + x];
    }

    setPositionZ(x: number, y: number, depth: number) {
        this.data[y*this.width + x] = depth;
        this.needUpdate = true;
    }

    protected beforeUpdate() {
        let max = Number.NEGATIVE_INFINITY, min = Number.POSITIVE_INFINITY;
        this.data.forEach(d => {
            if (d !== MaxZBuffer) {
                max = Math.max(d, max);
                min = Math.min(d, min);
            }
        });
        this.setRange(min, max);
    }

    protected elementFillToImage(dataOffset: number, imageOffset: number) {
        let d = 0;
        if (this.depth === 0 || this.data[dataOffset] === MaxZBuffer) {
            d = 0;
        } else {
            d = (this.max - this.data[dataOffset]) / this.depth * 255;
        }
        this.imageData.data[imageOffset + 0] = d;
        this.imageData.data[imageOffset + 1] = d;
        this.imageData.data[imageOffset + 2] = d;
        this.imageData.data[imageOffset + 3] = 255;
    }
}